home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / devel / lang / lisp / stk-3.002 / stk-3 / STk-3.1 / Tk / generic / tkImgPPM.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-05-31  |  10.8 KB  |  409 lines

  1. /*
  2.  * tkImgPPM.c --
  3.  *
  4.  *    A photo image file handler for PPM (Portable PixMap) files.
  5.  *
  6.  * Copyright (c) 1994 The Australian National University.
  7.  * Copyright (c) 1994-1996 Sun Microsystems, Inc.
  8.  *
  9.  * See the file "license.terms" for information on usage and redistribution
  10.  * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
  11.  *
  12.  * Author: Paul Mackerras (paulus@cs.anu.edu.au),
  13.  *       Department of Computer Science,
  14.  *       Australian National University.
  15.  *
  16.  * SCCS: @(#) tkImgPPM.c 1.13 96/03/18 14:56:41
  17.  */
  18.  
  19. #include "tkInt.h"
  20. #include "tkPort.h"
  21.  
  22. /*
  23.  * The maximum amount of memory to allocate for data read from the
  24.  * file.  If we need more than this, we do it in pieces.
  25.  */
  26.  
  27. #define MAX_MEMORY    10000        /* don't allocate > 10KB */
  28.  
  29. /*
  30.  * Define PGM and PPM, i.e. gray images and color images.
  31.  */
  32.  
  33. #define PGM 1
  34. #define PPM 2
  35.  
  36. /*
  37.  * The format record for the PPM file format:
  38.  */
  39.  
  40. static int        FileMatchPPM _ANSI_ARGS_((FILE *f, char *fileName,
  41.                 char *formatString, int *widthPtr,
  42.                 int *heightPtr));
  43. static int        FileReadPPM  _ANSI_ARGS_((Tcl_Interp *interp,
  44.                 FILE *f, char *fileName, char *formatString,
  45.                 Tk_PhotoHandle imageHandle, int destX, int destY,
  46.                 int width, int height, int srcX, int srcY));
  47. static int        FileWritePPM _ANSI_ARGS_((Tcl_Interp *interp,
  48.                 char *fileName, char *formatString,
  49.                 Tk_PhotoImageBlock *blockPtr));
  50.  
  51. Tk_PhotoImageFormat tkImgFmtPPM = {
  52.     "PPM",            /* name */
  53.     FileMatchPPM,        /* fileMatchProc */
  54.     NULL,            /* stringMatchProc */
  55.     FileReadPPM,        /* fileReadProc */
  56.     NULL,            /* stringReadProc */
  57.     FileWritePPM,        /* fileWriteProc */
  58.     NULL,            /* stringWriteProc */
  59. };
  60.  
  61. /*
  62.  * Prototypes for local procedures defined in this file:
  63.  */
  64.  
  65. static int        ReadPPMFileHeader _ANSI_ARGS_((FILE *f, int *widthPtr,
  66.                 int *heightPtr, int *maxIntensityPtr));
  67.  
  68. /*
  69.  *----------------------------------------------------------------------
  70.  *
  71.  * FileMatchPPM --
  72.  *
  73.  *    This procedure is invoked by the photo image type to see if
  74.  *    a file contains image data in PPM format.
  75.  *
  76.  * Results:
  77.  *    The return value is >0 if the first characters in file "f" look
  78.  *    like PPM data, and 0 otherwise.
  79.  *
  80.  * Side effects:
  81.  *    The access position in f may change.
  82.  *
  83.  *----------------------------------------------------------------------
  84.  */
  85.  
  86. static int
  87. FileMatchPPM(f, fileName, formatString, widthPtr, heightPtr)
  88.     FILE *f;            /* The image file, open for reading. */
  89.     char *fileName;        /* The name of the image file. */
  90.     char *formatString;        /* User-specified format string, or NULL. */
  91.     int *widthPtr, *heightPtr;    /* The dimensions of the image are
  92.                  * returned here if the file is a valid
  93.                  * raw PPM file. */
  94. {
  95.     int dummy;
  96.  
  97.     return ReadPPMFileHeader(f, widthPtr, heightPtr, &dummy);
  98. }
  99.  
  100. /*
  101.  *----------------------------------------------------------------------
  102.  *
  103.  * FileReadPPM --
  104.  *
  105.  *    This procedure is called by the photo image type to read
  106.  *    PPM format data from a file and write it into a given
  107.  *    photo image.
  108.  *
  109.  * Results:
  110.  *    A standard TCL completion code.  If TCL_ERROR is returned
  111.  *    then an error message is left in interp->result.
  112.  *
  113.  * Side effects:
  114.  *    The access position in file f is changed, and new data is
  115.  *    added to the image given by imageHandle.
  116.  *
  117.  *----------------------------------------------------------------------
  118.  */
  119.  
  120. static int
  121. FileReadPPM(interp, f, fileName, formatString, imageHandle, destX, destY,
  122.     width, height, srcX, srcY)
  123.     Tcl_Interp *interp;        /* Interpreter to use for reporting errors. */
  124.     FILE *f;            /* The image file, open for reading. */
  125.     char *fileName;        /* The name of the image file. */
  126.     char *formatString;        /* User-specified format string, or NULL. */
  127.     Tk_PhotoHandle imageHandle;    /* The photo image to write into. */
  128.     int destX, destY;        /* Coordinates of top-left pixel in
  129.                  * photo image to be written to. */
  130.     int width, height;        /* Dimensions of block of photo image to
  131.                  * be written to. */
  132.     int srcX, srcY;        /* Coordinates of top-left pixel to be used
  133.                  * in image being read. */
  134. {
  135.     int fileWidth, fileHeight, maxIntensity;
  136.     int nLines, nBytes, h, type, count;
  137.     unsigned char *pixelPtr;
  138.     Tk_PhotoImageBlock block;
  139.  
  140.     type = ReadPPMFileHeader(f, &fileWidth, &fileHeight, &maxIntensity);
  141.     if (type == 0) {
  142.     Tcl_AppendResult(interp, "couldn't read raw PPM header from file \"",
  143.         fileName, "\"", NULL);
  144.     return TCL_ERROR;
  145.     }
  146.     if ((fileWidth <= 0) || (fileHeight <= 0)) {
  147.     Tcl_AppendResult(interp, "PPM image file \"", fileName,
  148.         "\" has dimension(s) <= 0", (char *) NULL);
  149.     return TCL_ERROR;
  150.     }
  151.     if ((maxIntensity <= 0) || (maxIntensity >= 256)) {
  152.     char buffer[30];
  153.  
  154.     sprintf(buffer, "%d", maxIntensity);
  155.     Tcl_AppendResult(interp, "PPM image file \"", fileName,
  156.         "\" has bad maximum intensity value ", buffer,
  157.         (char *) NULL);
  158.     return TCL_ERROR;
  159.     }
  160.  
  161.     if ((srcX + width) > fileWidth) {
  162.     width = fileWidth - srcX;
  163.     }
  164.     if ((srcY + height) > fileHeight) {
  165.     height = fileHeight - srcY;
  166.     }
  167.     if ((width <= 0) || (height <= 0)
  168.     || (srcX >= fileWidth) || (srcY >= fileHeight)) {
  169.     return TCL_OK;
  170.     }
  171.  
  172.     if (type == PGM) {
  173.         block.pixelSize = 1;
  174.         block.offset[0] = 0;
  175.     block.offset[1] = 0;
  176.     block.offset[2] = 0;
  177.     }
  178.     else {
  179.         block.pixelSize = 3;
  180.         block.offset[0] = 0;
  181.     block.offset[1] = 1;
  182.     block.offset[2] = 2;
  183.     }
  184.     block.width = width;
  185.     block.pitch = block.pixelSize * fileWidth;
  186.  
  187.     Tk_PhotoExpand(imageHandle, destX + width, destY + height);
  188.  
  189.     if (srcY > 0) {
  190.     fseek(f, (long) (srcY * block.pitch), SEEK_CUR);
  191.     }
  192.  
  193.     nLines = (MAX_MEMORY + block.pitch - 1) / block.pitch;
  194.     if (nLines > height) {
  195.     nLines = height;
  196.     }
  197.     if (nLines <= 0) {
  198.     nLines = 1;
  199.     }
  200.     nBytes = nLines * block.pitch;
  201.     pixelPtr = (unsigned char *) ckalloc((unsigned) nBytes);
  202.     block.pixelPtr = pixelPtr + srcX * block.pixelSize;
  203.  
  204.     for (h = height; h > 0; h -= nLines) {
  205.     if (nLines > h) {
  206.         nLines = h;
  207.         nBytes = nLines * block.pitch;
  208.     }
  209.     count = fread(pixelPtr, 1, (unsigned) nBytes, f);
  210.     if (count != nBytes) {
  211.         Tcl_AppendResult(interp, "error reading PPM image file \"",
  212.             fileName, "\": ",
  213.             feof(f) ? "not enough data" : Tcl_PosixError(interp),
  214.             (char *) NULL);
  215.         ckfree((char *) pixelPtr);
  216.         return TCL_ERROR;
  217.     }
  218.     if (maxIntensity != 255) {
  219.         unsigned char *p;
  220.  
  221.         for (p = pixelPtr; count > 0; count--, p++) {
  222.         *p = (((int) *p) * 255)/maxIntensity;
  223.         }
  224.     }
  225.     block.height = nLines;
  226.     Tk_PhotoPutBlock(imageHandle, &block, destX, destY, width, nLines);
  227.     destY += nLines;
  228.     }
  229.  
  230.     ckfree((char *) pixelPtr);
  231.     return TCL_OK;
  232. }
  233.  
  234. /*
  235.  *----------------------------------------------------------------------
  236.  *
  237.  * FileWritePPM --
  238.  *
  239.  *    This procedure is invoked to write image data to a file in PPM
  240.  *    format.
  241.  *
  242.  * Results:
  243.  *    A standard TCL completion code.  If TCL_ERROR is returned
  244.  *    then an error message is left in interp->result.
  245.  *
  246.  * Side effects:
  247.  *    Data is written to the file given by "fileName".
  248.  *
  249.  *----------------------------------------------------------------------
  250.  */
  251.  
  252. static int
  253. FileWritePPM(interp, fileName, formatString, blockPtr)
  254.     Tcl_Interp *interp;
  255.     char *fileName;
  256.     char *formatString;
  257.     Tk_PhotoImageBlock *blockPtr;
  258. {
  259.     FILE *f;
  260.     int w, h;
  261.     int greenOffset, blueOffset, nBytes;
  262.     unsigned char *pixelPtr, *pixLinePtr;
  263.  
  264.     if ((f = fopen(fileName, "wb")) == NULL) {
  265.     Tcl_AppendResult(interp, fileName, ": ", Tcl_PosixError(interp),
  266.         (char *)NULL);
  267.     return TCL_ERROR;
  268.     }
  269.  
  270.     fprintf(f, "P6\n%d %d\n255\n", blockPtr->width, blockPtr->height);
  271.  
  272.     pixLinePtr = blockPtr->pixelPtr + blockPtr->offset[0];
  273.     greenOffset = blockPtr->offset[1] - blockPtr->offset[0];
  274.     blueOffset = blockPtr->offset[2] - blockPtr->offset[0];
  275.  
  276.     if ((greenOffset == 1) && (blueOffset == 2) && (blockPtr->pixelSize == 3)
  277.         && (blockPtr->pitch == (blockPtr->width * 3))) {
  278.     nBytes = blockPtr->height * blockPtr->pitch;
  279.     if (fwrite(pixLinePtr, 1, (unsigned) nBytes, f) != nBytes) {
  280.         goto writeerror;
  281.     }
  282.     } else {
  283.     for (h = blockPtr->height; h > 0; h--) {
  284.         pixelPtr = pixLinePtr;
  285.         for (w = blockPtr->width; w > 0; w--) {
  286.         if ((putc(pixelPtr[0], f) == EOF)
  287.             || (putc(pixelPtr[greenOffset], f) == EOF)
  288.             || (putc(pixelPtr[blueOffset], f) == EOF)) {
  289.             goto writeerror;
  290.         }
  291.         pixelPtr += blockPtr->pixelSize;
  292.         }
  293.         pixLinePtr += blockPtr->pitch;
  294.     }
  295.     }
  296.  
  297.     if (fclose(f) == 0) {
  298.     return TCL_OK;
  299.     }
  300.     f = NULL;
  301.  
  302.  writeerror:
  303.     Tcl_AppendResult(interp, "error writing \"", fileName, "\": ",
  304.         Tcl_PosixError(interp), (char *) NULL);
  305.     if (f != NULL) {
  306.     fclose(f);
  307.     }
  308.     return TCL_ERROR;
  309. }
  310.  
  311. /*
  312.  *----------------------------------------------------------------------
  313.  *
  314.  * ReadPPMFileHeader --
  315.  *
  316.  *    This procedure reads the PPM header from the beginning of a
  317.  *    PPM file and returns information from the header.
  318.  *
  319.  * Results:
  320.  *    The return value is PGM if file "f" appears to start with
  321.  *    a valid PGM header, PPM if "f" appears to start with a valid
  322.  *      PPM header, and 0 otherwise.  If the header is valid,
  323.  *    then *widthPtr and *heightPtr are modified to hold the
  324.  *    dimensions of the image and *maxIntensityPtr is modified to
  325.  *    hold the value of a "fully on" intensity value.
  326.  *
  327.  * Side effects:
  328.  *    The access position in f advances.
  329.  *
  330.  *----------------------------------------------------------------------
  331.  */
  332.  
  333. static int
  334. ReadPPMFileHeader(f, widthPtr, heightPtr, maxIntensityPtr)
  335.     FILE *f;            /* Image file to read the header from */
  336.     int *widthPtr, *heightPtr;    /* The dimensions of the image are
  337.                  * returned here. */
  338.     int *maxIntensityPtr;    /* The maximum intensity value for
  339.                  * the image is stored here. */
  340. {
  341. #define BUFFER_SIZE 1000
  342.     char buffer[BUFFER_SIZE];
  343.     int i, numFields, firstInLine, c;
  344.     int type = 0;
  345.  
  346.     /*
  347.      * Read 4 space-separated fields from the file, ignoring
  348.      * comments (any line that starts with "#").
  349.      */
  350.  
  351.     c = getc(f);
  352.     firstInLine = 1;
  353.     i = 0;
  354.     for (numFields = 0; numFields < 4; numFields++) {
  355.     /*
  356.      * Skip comments and white space.
  357.      */
  358.  
  359.     while (1) {
  360.         while (isspace(UCHAR(c))) {
  361.         firstInLine = (c == '\n');
  362.         c = getc(f);
  363.         }
  364.         if (c != '#') {
  365.         break;
  366.         }
  367.         do {
  368.         c = getc(f);
  369.         } while ((c != EOF) && (c != '\n'));
  370.         firstInLine = 1;
  371.     }
  372.  
  373.     /*
  374.      * Read a field (everything up to the next white space).
  375.      */
  376.  
  377.     while ((c != EOF) && !isspace(UCHAR(c))) {
  378.         if (i < (BUFFER_SIZE-2)) {
  379.         buffer[i]  = c;
  380.         i++;
  381.         }
  382.         c = getc(f);
  383.     }
  384.     if (i < (BUFFER_SIZE-1)) {
  385.         buffer[i] = ' ';
  386.         i++;
  387.     }
  388.     firstInLine = 0;
  389.     }
  390.     buffer[i] = 0;
  391.  
  392.     /*
  393.      * Parse the fields, which are: id, width, height, maxIntensity.
  394.      */
  395.  
  396.     if (strncmp(buffer, "P6 ", 3) == 0) {
  397.     type = PPM;
  398.     } else if (strncmp(buffer, "P5 ", 3) == 0) {
  399.     type = PGM;
  400.     } else {
  401.     return 0;
  402.     }
  403.     if (sscanf(buffer+3, "%d %d %d", widthPtr, heightPtr, maxIntensityPtr)
  404.         != 3) {
  405.     return 0;
  406.     }
  407.     return type;
  408. }
  409.